package com.juntuo.controller;

import com.gargoylesoftware.htmlunit.WebClient;
import com.github.pagehelper.PageInfo;
import com.juntuo.Enums.CertStatus;
import com.juntuo.Enums.InstitutionStatus;
import com.juntuo.entity.Cert;
import com.juntuo.entity.CertCdf;
import com.juntuo.entity.CertRelationship;
import com.juntuo.entity.User;
import com.juntuo.entity.vo.CertResult;
import com.juntuo.service.CdfCertService;
import com.juntuo.service.CertRelationshipService;
import com.juntuo.service.CertService;
import com.juntuo.service.UserService;
import com.juntuo.shiro.ShiroUtil;
import com.juntuo.util.CertificateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/cert")
public class CertController {

    @Autowired
    private CertService certService;
    @Autowired
    private UserService userService;
    @Autowired
    private CertRelationshipService certRelationshipService ;
    @Autowired
    private CdfCertService cdfCertService;
    @RequestMapping("/index")
    public String toIndex(){
        return "/cert/index";
    }

    @RequestMapping("/page")
    @ResponseBody
    public PageInfo<Map<String,Object>> getPage(int pageNumber, int pageSize, String number, @RequestParam(defaultValue = "0") Integer institution, @RequestParam(defaultValue = "-1") Integer status){
        User user = ShiroUtil.currentUser();
        Integer ownerId=0;
        if(user.getUsername().indexOf("admin")<0){
            ownerId=user.getFatherId()==null?user.getId():user.getFatherId();
        }


        return certService.findPagedCerts(pageNumber,pageSize,number,institution,status,ownerId);
    }

    @RequestMapping("/save")
    @ResponseBody
    public boolean saveOne(Integer id,String number,Integer institution){
        number = number.replaceAll("\\s*", "").toUpperCase();
        Cert cert = new Cert();
        cert.setNumber(number);
        cert.setInstitutionCode(institution);
        cert.setInstitutionName(InstitutionStatus.getByStatus(institution).getDesc());

        if(id==null || id ==0){
            cert.setValid(CertStatus.WAITING.getCode());//这里默认为0 暂时不知是有效还是无效
            cert.setStatus(0);//默认为0  是正常的
            User user = ShiroUtil.currentUser();
            Integer ownerId=user.getFatherId()==null?user.getId():user.getFatherId();
            cert.setUserId(ownerId);
            certService.insert(cert);
        }else{
            cert.setId(id);
            cert.setUpdateTime(new Date());
            certService.updateByPrimaryKey(cert);
        }
        return true;
    }


    @RequestMapping("/delete/{id}")
    @ResponseBody
    public int deleteOne(@PathVariable int id){
        Cert cert = new Cert();
        cert.setId(id);
        cert.setValid(CertStatus.DELETED.getCode());
        certService.updateByPrimaryKeySelective(cert);
        return 1;
    }

    @RequestMapping("/fresh/{id}")
    @ResponseBody
    public int freshOne(@PathVariable int id){
        Cert cert = certService.selectByPrimaryKey(id);
        if(cert.getUpdateTime()!=null && (new Date().getTime()-cert.getUpdateTime().getTime())<24*60*60*1000){
            return 0;
        }
        PageInfo<Map<String,Object>> res=cdfCertService.findPagedCertsByMainCertId(1,1000,id,null,0,-10);
        if(res.getTotal()>0){
            List<Map<String,Object>> maps = res.getList();
            WebClient webClient = CertificateUtils.startAClient();
            for(Map<String,Object> map :maps){

                String number = map.get("number").toString();
                Date updateTime = (Date) map.get("update_time");
                Integer code = Integer.parseInt(map.get("institution_code").toString());
                Integer ccid = Integer.parseInt(map.get("ccid").toString());//cdf证书id
                if(updateTime==null ||(new Date().getTime()-updateTime.getTime())>24*60*60*1000){
                    CertCdf certCdf = new CertCdf();
                    certCdf.setId(ccid);
                    CertResult result = CertificateUtils.searchByCode(webClient,number,code);
                    certCdf.setValid(result.getResult());
                    certCdf.setUpdateTime(new Date());
                    if(result.getResult()==CertStatus.OK.getCode()){
                        if(result.getCompanyName()!=null){
                            certCdf.setHolderName(result.getCompanyName());
                        }
                        if(result.getProduct()!=null){
                            certCdf.setProducts(result.getProduct());
                        }
                        if(result.getModel()!=null){
                            certCdf.setModel(result.getModel());
                        }

                    }
                    cdfCertService.updateByPrimaryKeySelective(certCdf);
                }
            }
            CertificateUtils.detroyWebClient(webClient);
        }else{
            System.out.println("该证书下无cdf");
            return 0;
        }
        return 1;
    }
}
